<template>
	<view class="web-wrap">
		<view class="web-cont">
			<!-- 雷达扫码开始 -->
			<radar :imageUrl="imageUrl"></radar>
			<!-- 雷达扫码结束 -->

			<view class="web-text">
				<view>{{$t('home.Bluetooth-prompt1')}}</view>
				<view>{{$t('home.Bluetooth-prompt2')}}</view>
			</view>
		</view>

		<view class="web-item">
			<view class="web-title flex">
				<view>{{$t('home.Searching-for-devices')}}</view>
				<uni-load-more class="icon-zq" :status="status" :content-text="contentText" iconSize="18" />
			</view>
			<view class="item-box">
				<view class="item" :class="[isActive == index ? 'active' : '']" v-for="(item, index) in bluetoothList"
					@click="connetBlue(item.deviceId,index)" :key="index">{{item.name}}</view>
			</view>
		</view>

	</view>
</template>

<script>
	import radar from '@/componets/radar.vue';
	export default {
		components: {
			radar
		},
		data() {
			return {
				status: 'loading', //加载中样式
				contentText: {
					contentdown: '',
					contentrefresh: '',
					contentnomore: ''
				}, //加载中文字
				imageUrl: 'https://be.coucoq.cn/jueli/static/2025/01/07/f82c3b7d-bd9e-4a43-a3b8-a205d7493622.png',
				time: null, // 定时获取蓝牙列表
				bluetoothList: [], // 搜索到的蓝牙列表
				deviceId: '', // 选中蓝牙
				services: '', // 当前连接蓝牙服务
				readyservices: '', //特征值
				isActive: -1,
				noty: ''
			}
		},
		onShow() {
			clearInterval(this.time)
			this.startBluetooth(); // 开始搜索蓝牙
		},
		onHide() {
			clearInterval(this.time);
			this.time = null;
		},
		onUnload() {
			clearInterval(this.time);
			this.time = null;
		},
		methods: {
			// 关闭蓝牙模块
			closeBluetooth() {
				uni.closeBluetoothAdapter({
					success(res) {
						console.log('关闭蓝牙模块==', res)
					}
				})
			},
			// 开始搜索蓝牙
			startBluetooth() {
				var that = this;
				that.closeBluetooth(); //先清除再打开
				uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
					success: function(res) {
						console.log("已经打开了了蓝牙")
						that.findBlue(); //2.0
					},
					fail: function(err) { //如果手机上的蓝牙没有打开，可以提醒用户		
						console.log("初始化--未开蓝牙-请打开蓝牙==", err)
						switch (uni.getSystemInfoSync().platform) {
							case 'android':
								// 如果是安卓
								// 跳转系统蓝牙设置页。仅支持安卓
								uni.openSystemBluetoothSetting({
									success: function(res) {
										console.log("打开设置", res);
									},
								})
								break;
							case 'ios':
								// 如果是ios
								// 跳转系统微信授权管理页
								uni.openAppAuthorizeSetting({
									success(res) {
										console.log(res)
									}
								})
								break;
						}
						// uni.showToast({
						// 	title: '请打开蓝牙',
						// 	type: 'error',
						// 	duration: 5000
						// });
					}
				})
			},
			// 搜索蓝牙
			findBlue() {
				var that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success: function(res) {
						console.log(res, '搜索')
						that.timingGetBlue() //定时刷新搜索到的蓝牙列表
					}
				})
			},
			// 定时刷新搜索到的蓝牙列表
			timingGetBlue() {
				// 每两秒执行一次搜索蓝牙
				clearInterval(this.time)
				this.time = setInterval(() => {
					console.log("每5秒执行一次搜索蓝牙")
					this.getBlue();
				}, 5000);
			},
			// 获取已搜索到的蓝牙列表
			getBlue() {
				var that = this
				this.bluetoothList = [];
				//uni.getBluetoothDevices获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
				uni.getBluetoothDevices({
					success: function(res) {
						console.log(res, '获取到的蓝牙列表');
						if (res.devices.length != 0) {
							// console.log(res.devices, '附近蓝牙列表')
							res.devices.forEach(k => {
								if (k.localName) {
									// console.log(k, '附近蓝牙名称')
									that.bluetoothList.push(k)
								}
								// console.log(name.toUpperCase(), k.name.toUpperCase(), '想通')
								//判断二维码上的name是否与蓝牙name一致
							})
						} else {
							that.getBlue() //3.0
						}
						//将BluetoothList遍历给用户，当用户点击连接某个蓝牙时调用4.0
					},
					fail: function(e) {
						console.log("搜索蓝牙设备失败")
					}
				})
			},
			// 选中所连接蓝牙
			connetBlue(dId, index) {
				console.log(dId, '连接当前选中蓝牙')
				if (this.isActive != index) {
					this.isActive = index;
				}


				return new Promise((resolve, reject) => {
					var that = this;

					uni.createBLEConnection({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: dId, //设备id
						success: function(res) {
							// uni.hideLoading();
							clearInterval(that.time)
							that.deviceId = dId;
							uni.stopBluetoothDevicesDiscovery({
								success: function(res) {
									console.log('连接蓝牙成功之后关闭蓝牙搜索');
								}
							})
							that.getServiceId() //5.0
						},
						fail: function(e) {
							that.config.Toast('连接失败，正在重新搜索')
							console.log("蓝牙连接设备失败", e)
						}
					})
				})
			},
			// 获取蓝牙设备所有服务
			getServiceId() {
				var that = this
				let readyservices = '';
				let noty = '';
				uni.getBLEDeviceServices({
					deviceId: that.deviceId,
					success: function(res) {
						console.log('获取蓝牙设备所有服务1111==', res)
						//因设备而议：该特征值支持write和notfy服务
						that.services = res.services[0].uuid;
						// 获取特征值
						uni.getBLEDeviceCharacteristics({
							deviceId: that.deviceId,
							// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
							serviceId: res.services[0].uuid,
							success: function(res2) {
								// 读取特征值  

								// that.readyservices = res2.characteristics[0].uuid;
								// readyservices  = res2.characteristics[0].uuid;

								console.log('特征值==', res2);

								for (var i = 0; i < res2.characteristics.length; i++) { //2个值
									var model = res2.characteristics[i]
									if (model.properties.write) {
										readyservices = model.uuid
									}
									if (model.properties.notify) {
										//model.uuid:用来notify的uuid值
										noty = model.uuid
										that.noty = model.uuid
										that.startNotice()
									}
								}
								console.log('noty==', noty)
								console.log('readyservices==', readyservices)
								uni.showToast({
									title: '蓝牙连接成功',
									icon: 'success',
									duration: 800
								})

								clearInterval(that.time)

								setTimeout(() => {
									that.config.path(
										'/pagesA/device/wifiNet/wifiNet?services=' +
										`${that.services}&deviceId=${that.deviceId}&readyservices=${readyservices}&noty=${noty}`
									)
								}, 1000)
							}
						});
					}
				})
			},
			startNotice(readyservices) {
				var that = this;
				console.log('111', 'deviceId==', that.deviceId, 'services服务==', that.services, 'readyservices特征==',
					readyservices)
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.services,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.noty, //第一步 开启监听 notityid  第二步发送指令 write
					success(res) {
						console.log('接受消息111', res)
					},
					fail(err) {
						console.log('接消息失败111', err)
					}
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	.web-wrap {
		.web-cont {
			background: #E0DAC9;

			.web-text {
				line-height: 49rpx;
				font-size: 30rpx;
				text-align: center;
				margin-top: 80rpx;
			}
		}

		.web-item {
			background-image: linear-gradient(to bottom, #E0DAC9, rgba(243, 238, 230, 0.1));
			margin: auto;
			padding: 50rpx 0;
			font-size: 30rpx;

			.web-title {
				width: 90%;
				margin: 20rpx auto;

				.icon-zq {
					margin-left: 10rpx;
				}
			}

			.item-box {
				width: 90%;
				margin: auto;
				background: #fff;
				border-radius: 15rpx;

				.item {
					line-height: 100rpx;
					border-bottom: 1rpx solid #f5f5f5;
					padding: 0 40rpx;
					color: #666666;
				}
			}
		}
	}

	.active {
		background: #f5f5f5;
	}
</style>